package com.citywithincity.db.sync;

import java.util.List;

import org.apache.http.util.TextUtils;

import com.citywithincity.db.DBException;
import com.citywithincity.db.Db;
import com.citywithincity.db.Page;
import com.citywithincity.db.Record;
import com.citywithincity.db.interfaces.Ar;
import com.citywithincity.utils.StringUtils;

public class SyncProgressPage implements ISyncData {
	private int srcDb;
	private String srcTable;
	private String[] srcFields;
	private SyncFieldsContainer container;
	private SyncInsertMethod insert;
	private SyncCondition condition;
	
	private int pageSize;
	
	private String extraFields;
	
	public SyncProgressPage(int srcDb,String srcTable,String[] srcFields,SyncFieldsContainer container,SyncInsertMethod insert,SyncCondition condition,int pageSize,String extraFields){
		this.condition = condition;
		this.container = container;
		this.insert = insert;
		this.srcDb = srcDb;
		this.srcFields = srcFields;
		this.srcTable = srcTable;
		this.pageSize = pageSize;
		this.extraFields = extraFields;
	}
	@Override
	public void destroy() {
		
	}
	@Override
	public void syncData() throws DBException {
		
		condition.init();
		
		String f = StringUtils.join(srcFields);
		if(!TextUtils.isEmpty(extraFields)){
			f = f + "," + extraFields;
		}
		Ar ar = Db.ar(srcDb);
		ar.select(f);
		condition.setAr(ar);
		int position = 0;
		Page<Record> page = ar.position(srcTable,position,pageSize);
		container.syncList( insert, page.getList());
		for(int i=1 , c = page.getTotalPages() ; i < c  ; ++i){
			ar.select(f);
			condition.setAr(ar);
			List<Record> list = ar.limit(srcTable, i * pageSize,   pageSize );
			container.syncList( insert, list);
		}
		
	}
	

}
